const fs = require('fs');
const path = require('path');

/**
 * Swagger注释生成器
 */
class SwaggerGenerator {
  /**
   * 为路由自动生成Swagger注释
   * @param {string} method - HTTP方法 (GET, POST, PUT, DELETE)
   * @param {string} path - 路由路径
   * @param {string} summary - 接口描述
   * @param {string} tag - 标签名称
   * @param {Object} options - 其他选项
   */
  static generateRouteDoc(method, path, summary, tag, options = {}) {
    const {
      parameters = [],
      requestBody = null,
      responses = {},
      description = ''
    } = options;

    let swaggerDoc = `/**\n * @swagger\n`;
    swaggerDoc += ` * ${path}:\n`;
    swaggerDoc += ` *   ${method.toLowerCase()}:\n`;
    swaggerDoc += ` *     summary: ${summary}\n`;
    swaggerDoc += ` *     tags: [${tag}]\n`;
    
    if (description) {
      swaggerDoc += ` *     description: ${description}\n`;
    }

    // 添加参数
    if (parameters.length > 0) {
      swaggerDoc += ` *     parameters:\n`;
      parameters.forEach(param => {
        swaggerDoc += ` *       - in: ${param.in}\n`;
        swaggerDoc += ` *         name: ${param.name}\n`;
        if (param.required) swaggerDoc += ` *         required: ${param.required}\n`;
        swaggerDoc += ` *         schema:\n`;
        swaggerDoc += ` *           type: ${param.type}\n`;
        if (param.description) swaggerDoc += ` *         description: ${param.description}\n`;
        if (param.default !== undefined) swaggerDoc += ` *           default: ${param.default}\n`;
        if (param.enum) swaggerDoc += ` *           enum: [${param.enum.map(v => `'${v}'`).join(', ')}]\n`;
      });
    }

    // 添加请求体
    if (requestBody) {
      swaggerDoc += ` *     requestBody:\n`;
      swaggerDoc += ` *       required: true\n`;
      swaggerDoc += ` *       content:\n`;
      swaggerDoc += ` *         application/json:\n`;
      swaggerDoc += ` *           schema:\n`;
      if (requestBody.ref) {
        swaggerDoc += ` *             $ref: '#/components/schemas/${requestBody.ref}'\n`;
      } else if (requestBody.type) {
        swaggerDoc += ` *             type: ${requestBody.type}\n`;
        if (requestBody.properties) {
          swaggerDoc += ` *             properties:\n`;
          Object.entries(requestBody.properties).forEach(([key, prop]) => {
            swaggerDoc += ` *               ${key}:\n`;
            swaggerDoc += ` *                 type: ${prop.type}\n`;
            if (prop.description) swaggerDoc += ` *                 description: ${prop.description}\n`;
          });
        }
      }
    }

    // 添加响应
    const defaultResponses = {
      200: { description: '操作成功' },
      400: { description: '请求参数错误' },
      500: { description: '服务器内部错误' },
      ...responses
    };

    swaggerDoc += ` *     responses:\n`;
    Object.entries(defaultResponses).forEach(([code, response]) => {
      swaggerDoc += ` *       ${code}:\n`;
      swaggerDoc += ` *         description: ${response.description}\n`;
      if (response.schema) {
        swaggerDoc += ` *         content:\n`;
        swaggerDoc += ` *           application/json:\n`;
        swaggerDoc += ` *             schema:\n`;
        if (response.schema.startsWith('#/') || response.schema.includes('schemas/')) {
          swaggerDoc += ` *               $ref: '${response.schema}'\n`;
        } else {
          swaggerDoc += ` *               $ref: '#/components/schemas/${response.schema}'\n`;
        }
      }
    });

    swaggerDoc += ` */\n`;
    return swaggerDoc;
  }

  /**
   * 生成完整的路由文档模板
   * @param {Array} routes - 路由配置数组
   * @param {string} tagName - 标签名称
   * @param {string} tagDescription - 标签描述
   */
  static generateCompleteDoc(routes, tagName, tagDescription) {
    let completeDoc = `/**\n * @swagger\n * tags:\n *   name: ${tagName}\n *   description: ${tagDescription}\n */\n\n`;
    
    routes.forEach(route => {
      completeDoc += this.generateRouteDoc(
        route.method,
        route.path,
        route.summary,
        tagName,
        route.options
      );
      completeDoc += '\n';
    });
    
    return completeDoc;
  }

  /**
   * 为现有路由文件添加Swagger注释
   * @param {string} filePath - 路由文件路径
   * @param {Array} routes - 路由配置数组
   */
  static async addSwaggerToFile(filePath, routes) {
    try {
      if (!fs.existsSync(filePath)) {
        console.error(`❌ 文件不存在: ${filePath}`);
        return false;
      }

      let content = fs.readFileSync(filePath, 'utf8');
      let modified = false;
      
      routes.forEach(route => {
        const swaggerDoc = this.generateRouteDoc(
          route.method,
          route.path,
          route.summary,
          route.tag,
          route.options
        );
        
        // 构建路由匹配模式
        const escapedPath = route.path.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
        const routePattern = new RegExp(
          `(\\s*)(router\\.${route.method.toLowerCase()}\\s*\\(\\s*['"\`]${escapedPath}['"\`])`,
          'g'
        );
        
        // 检查是否已经有Swagger注释
        const beforeRoutePattern = new RegExp(
          `\/\\*\\*[\\s\\S]*?@swagger[\\s\\S]*?\\*\/\\s*router\\.${route.method.toLowerCase()}\\s*\\(\\s*['"\`]${escapedPath}['"\`]`,
          'g'
        );
        
        if (!beforeRoutePattern.test(content)) {
          content = content.replace(routePattern, (match, indent, routerCall) => {
            modified = true;
            return `${indent}${swaggerDoc}${routerCall}`;
          });
        } else {
          console.log(`⚠️ 路由 ${route.method} ${route.path} 已存在Swagger注释，跳过`);
        }
      });
      
      if (modified) {
        fs.writeFileSync(filePath, content, 'utf8');
        console.log(`✅ 已为 ${filePath} 添加Swagger注释`);
        return true;
      } else {
        console.log(`ℹ️ 文件 ${filePath} 无需修改`);
        return false;
      }
    } catch (error) {
      console.error(`❌ 处理文件 ${filePath} 时出错:`, error.message);
      return false;
    }
  }

  /**
   * 生成新的路由文件模板
   * @param {string} fileName - 文件名
   * @param {string} tagName - 标签名称
   * @param {string} tagDescription - 标签描述
   * @param {Array} routes - 路由配置
   */
  static generateRouteFileTemplate(fileName, tagName, tagDescription, routes) {
    let template = `const express = require('express');\nconst router = express.Router();\n\n`;
    
    // 添加标签定义
    template += `/**\n * @swagger\n * tags:\n *   name: ${tagName}\n *   description: ${tagDescription}\n */\n\n`;
    
    // 添加每个路由
    routes.forEach(route => {
      template += this.generateRouteDoc(
        route.method,
        route.path,
        route.summary,
        tagName,
        route.options
      );
      
      template += `router.${route.method.toLowerCase()}('${route.path}', async (req, res) => {\n`;
      template += `  try {\n`;
      template += `    // TODO: 实现 ${route.summary}\n`;
      template += `    res.json({\n`;
      template += `      success: true,\n`;
      template += `      message: '${route.summary}成功',\n`;
      template += `      data: {}\n`;
      template += `    });\n`;
      template += `  } catch (error) {\n`;
      template += `    console.error('❌ ${route.summary}失败:', error);\n`;
      template += `    res.status(500).json({\n`;
      template += `      success: false,\n`;
      template += `      message: '${route.summary}失败'\n`;
      template += `    });\n`;
      template += `  }\n`;
      template += `});\n\n`;
    });
    
    template += `module.exports = router;\n`;
    
    return template;
  }
}

module.exports = SwaggerGenerator;